package com.ruoyi.user.sms.util;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 国阳云短信服务 HttpUtils
 * 基于阿里云 API Gateway 示例代码修改
 */
public class HttpUtils {
    
    /**
     * 发送 POST 请求
     */
    public static HttpResponse doPost(String host, String path, String method,
                                   Map<String, String> headers, Map<String, String> querys,
                                   Map<String, String> bodys) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(host + path + "?" + buildQueryString(querys));
        
        // 设置请求头
        for (Map.Entry<String, String> e : headers.entrySet()) {
            httpPost.addHeader(e.getKey(), e.getValue());
        }
        
        // 设置请求体
        if (bodys != null && !bodys.isEmpty()) {
            List<NameValuePair> nameValuePairList = new ArrayList<>();
            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList, "utf-8"));
        }
        
        return httpClient.execute(httpPost);
    }
    
    /**
     * 构建查询字符串
     */
    private static String buildQueryString(Map<String, String> querys) throws Exception {
        if (querys == null || querys.isEmpty()) {
            return "";
        }
        
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String, String> e : querys.entrySet()) {
            if (!first) {
                sb.append("&");
            }
            first = false;
            sb.append(URLEncoder.encode(e.getKey(), "utf-8"));
            sb.append("=");
            sb.append(URLEncoder.encode(e.getValue(), "utf-8"));
        }
        return sb.toString();
    }
}
